// 引入SDK核心类
var amapFile = require('../libs/amap-wx.130.js');
var myAmapFun = new amapFile.AMapWX({
  key: getApp().data.amapKey
});

export const API_URI = getApp().data.servsers +"/android";

// ["预约任务", "我的任务", "已完成任务"]
const taskListUrl = ["/surveydistribut/listjsonforApp.shtml", "/surveydistribut/listjsonforApp.shtml", "/surveydistribut/listjsonforApp.shtml"];



function getPoiAround() {
  return myAmapFun.getPoiAround({
    iconPathSelected: '选中 marker 图标的相对路径', //如：..­/..­/img/marker_checked.png
    iconPath: '未选中 marker 图标的相对路径', //如：..­/..­/img/marker.png
  })
}

// 调用异步接口
function promisify(api){
  return (options, ...params) => {
    return new Promise((resolve, reject) => {
      api(Object.assign({}, options, { success: resolve, fail: err => {
        wx.showToast({
          title: "网络异常",
          icon: "none"
        });
        reject(err);
      } }), ...params);
    });
  }
}

// 请求服务器接口
function fetchApi(url, params, method, header={}) {
  var token = wx.getStorageSync("token");
  header.token = token;
  return promisify(wx.request)({
    url: `${API_URI}/${url}`,
    method: method || "GET",
    data: params,
    header: header
  }).then(res => {
    if (res.statusCode == 200) {
      let data = res.data;
      if (data.code != 0) {
        wx.showToast({
          title: data.msg ? data.msg : "系统异常",
          icon: "none"
        });
        // 如果token失效，返回到登录页
        if (data.code == 300) {
          setTimeout(function () {
            logout();// 退出登录
          }, 1500);
          throw Error
        }
      }
      return data;
    } else {
      wx.showToast({
        title: "系统异常",
        icon: "none"
      });
      throw Error
    }
  });
}

// 请求服务器接口2
function fetchApi2(url, params, method, header = {}) {
  var token = wx.getStorageSync("token");
  header.token = token;
  return promisify(wx.request)({
    url: `${API_URI}/${url}`,
    method: method || "GET",
    data: params,
    header: header
  }).then(res => {
    if (res.statusCode == 200) {
      let data = res.data;
      // 如果token失效，返回到登录页
      if (data.code == 300) {
        wx.showToast({
          title: data.msg,
          icon: "none"
        });
        setTimeout(function () {
          logout();// 退出登录
        }, 1500);
        throw Error
      }
      return res;
    } else {
      wx.showToast({
        title: "系统异常",
        icon: "none"
      });
      throw Error
    }
  });
}

// 登录
function login(account, password){
  wx.showLoading({
    title: "正在登录",
  });
  return fetchApi("login/login.shtml", {
    body: {
      "account": account,
      "password": password
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      wx.hideLoading();
      var data = res.data;
      //将用户数据放入本地缓存
      try {
        wx.setStorageSync("token", data.token);
        wx.setStorageSync("userId", data.userId);
        wx.setStorageSync("companyId", data.companyId);
        wx.setStorageSync("companyName", data.companyName);
        wx.setStorageSync("name", data.name);
        wx.setStorageSync("roleList", data.roleList);
      } catch (e) {
      }
      wx.showToast({
        title: "登录成功",
        icon: "none",
        duration: 1000
      });
      setTimeout(function () {
        wx.reLaunch({
          url: "../index/index"
        });
      }, 1000);
    }
  });
}


// 退出登录
function logout(){
  console.log("到这里了！")
  try {
    wx.removeStorageSync("token");
    wx.removeStorageSync("userId");
    wx.removeStorageSync("companyId");
    wx.removeStorageSync("companyName");
    wx.removeStorageSync("name");
    wx.removeStorageSync("roleList");
    wx.reLaunch({
      url: "/pages/login/login"
    });
  } catch (e) {
    // Do something when catch error
  }
}

// 获取权限信息
function getUserRole() {
  var userId = wx.getStorageSync("userId");
  return fetchApi("login/queryPower?userId=" + userId, {
  }, "POST");
}

// 获取今日出行打卡记录
function getClockInRecord() {
  var userId = wx.getStorageSync("userId");
  return fetchApi("clockout/queryAlready?userId=" + userId, {
  }, "POST");
}

// 获取今日外访相关
function getVisitToday() {
  var userId = wx.getStorageSync("userId");
  return fetchApi2("clockout/visit_today", {
    body:{
      "userId": userId
    }
  }, "POST");
}

// 出行打卡
function clockIn(params) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("clockout/add_clock", {
    body: {
      "userId": userId,
      ...params
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      wx.hideLoading();
      wx.navigateBack({
        delta: 2,
        success: function () {
          wx.showToast({
            title: "打卡成功"
          });
        }
      });
    }
  });
}

// 获取任务列表
function getTaskList(nowPage, pagesize, state, keyword){
  // 获取接口路径
  var url = "/surveydistribut/listjsonforApp.shtml";
  const longitude = 0;
  const latitude = 0;

  // 获取任务列表
  var userId = wx.getStorageSync("userId");
  var companyId = wx.getStorageSync("companyId");
  return fetchApi(url, {
    body: {
      "orgid": companyId,
      "userid": userId,
      "state": state,
      "manyno": null,
      "keyword":keyword,
    },
    header: {
      "nowPage": nowPage,
      "pagesize": pagesize
    }
  }, "POST");
}

function getAllTaskList(nowPage, pagesize, state, keyword){
  // 获取接口路径
  var url = "/surveydistribut/alllistjsonforApp.shtml";
  const longitude = 0;
  const latitude = 0;

  // 获取任务列表
  var userId = wx.getStorageSync("userId");
  var companyId = wx.getStorageSync("companyId");
  return fetchApi(url, {
    body: {
      "orgid": companyId,
      "state": state,
      "manyno": null,
      "keyword":keyword,
    },
    header: {
      "nowPage": nowPage,
      "pagesize": pagesize
    }
  }, "POST");
}

// 获取任务列表
function getAppointmentList(nowPage, pagesize, custName, completeTime, collerName){
  // 获取接口路径
  var url = "/surveydistribut/listjsonforApp.shtml";
  const longitude = 0;
  const latitude = 0;

    // 获取任务列表
    var userId = wx.getStorageSync("userId");
    var companyId = wx.getStorageSync("companyId");
    return fetchApi(url, {
      body: {
        "orgid": companyId,
        "latitude": latitude,
        "longitude": longitude,
        "userid": userId,
        "state": "0",
        "manyno": null
      },
      header: {
        "nowPage": nowPage,
        "pagesize": pagesize
      }
    }, "POST");
  // });
}

// 延时外访
function delayedOut(id, cause) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("applyOutvisit/delayedOut", {
    body: {
      "userId": userId,
      "outvisitTaskId": id,
      "delayedReason": cause
    }
  }, "POST");
}

function copyValues(id, copyId) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("/surveydistribut/copyValuesforApp.shtml", {
    body: {
      "userId": userId,
      "id": id,
      "copyId": copyId
    }
  }, "POST");
}

// 抢单
function scrambleAlone(outvisitTaskId) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("outvisit/rob_task", {
    body: {
      "outvisitTaskId": outvisitTaskId,
      "userId": userId
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      wx.hideLoading();
      // 获取上一个页面
      var pages = getCurrentPages();
      var page = pages[pages.length - 2];
      wx.navigateBack({
        delta: 1,
        success: function () {
          wx.showToast({
            title: "抢单成功"
          });
          // 刷新附近任务列表页
          if (page.data.type == 2) {
            page.updateList();
            // 刷新地图页
          } else if (page.data.type == 0) {
            page.getTaskList();
            page.setData({
              taskInfoIsHide: true
            });
          }
        }
      });
    }
  });
}

// 获取任务详情
function getTaskDetails(id) {
  return fetchApi("outvisit/task_detail", {
    body: {
      "outvisitTaskId": id
    }
  }, "POST");
}

// 获取任务详情
function getAppointmentDetails(id) {
  return fetchApi("surveydistribut/getdisobjinfoforApp.shtml", {
    body: {
      "id": id
    }
  }, "POST");
}

//获取查勘要素清单
function getSuveyColumnVal(id,pid) {
  return fetchApi("surveydistribut/getSuveyColumnVal.shtml", {
    body: {
      "distributid": id,
      "pid": pid
    }
  }, "POST");
}

function getSuveyColumnValForAddCase(id,pid) {
  return fetchApi("surveydistribut/getSuveyColumnValForAddCase.shtml", {
    body: {
      "distributid": id,
      "pid": pid
    }
  }, "POST");
}

//获取查勘要素父级列表
function getSuveyColumnList() {
  //var userId = wx.getStorageSync("userId");
  //data.userId = userId;
  return fetchApi("surveydistribut/getSuveyColumnList.shtml", {
  }, "POST");
}

function getUsfulAmapInfo() {
  return fetchApi("surveydistribut/getAmapInfo.shtml", {
  }, "POST");
}

// 签到打卡
function saveBigMapImage(id, longitude, latitude) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("surveydistribut/saveBigMapImage.shtml", {
    body: {
      location: longitude+","+latitude,
      distributid: id,
      userId: userId,
      key: getApp().data.amapWebServiceKey,
    }
  }, "POST");
}

function saveSmallMapImage(id, longitude, latitude) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("surveydistribut/saveSmallMapImage.shtml", {
    body: {
      location: longitude+","+latitude,
      distributid: id,
      userId: userId,
      key: getApp().data.amapWebServiceKey,
    }
  }, "POST");
}

//根据位置名称获取坐标
function getLocationByName(address,amapWebServiceKey) {
  console.log("address===============================>"+address);
  console.log("amapWebServiceKey===============================>"+amapWebServiceKey);
  return new Promise((resolve, reject) => {
    // 高德地图
    wx.request({
      url: getApp().data.amapGeo,
      data: {
          address: address,
          output: 'json',
          key: amapWebServiceKey
      },
      header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
          let result="";
          console.log("res===============================>");
          console.log(res);
          if(res.data.status == 1 && res.data.geocodes.length > 0){
              console.log("返回编号信息");
              let geoAddressLocation = res.data.geocodes[0].location;
              console.log(geoAddressLocation.location);
              let lng = geoAddressLocation.split(",")[0];//经度
              let lat = geoAddressLocation.split(",")[1];//纬度
              result={"location" : {"lng": lng, "lat": lat}};
              console.log(result);
          }else{
              console.log("返回超时或未找到地址编码");
              result = {"location" : {"lng": "", "lat": ""}}
          }
          res["result"]=result;
          resolve(res);
      },
      fail: function (err) {
          wx.showToast({
              title: "获取坐标失败",
              icon: "none"
          });
          reject(err);
          }
      });
  });
}

//根据坐标获取位置名称
function getLocationName(longitude, latitude){
  return new Promise((resolve, reject) => {
    //高德地图
    myAmapFun.getRegeo({
        location: '' + longitude + ',' + latitude + '',
        success: function (addressRes) {
            console.log(addressRes);
            //var address = addressRes[0].regeocodeData.formatted_address;//当前位置名称
            var address = addressRes[0].name;//当前位置名称
            resolve(address);
        }, fail: function (err) {
          wx.showToast({
            title: "获取位置失败",
            icon: "none"
          });
          reject(err);
        }
      });
  });
}


function updateAmapTimes(amapWebServiceKey){
  return fetchApi("surveydistribut/updateAmapTimesApp.shtml", {
    body: {
      amapWebServiceKey: amapWebServiceKey,
    }
  }, "POST");
}

//根据坐标获取位置名称
function getRoundInfo1(longitude, latitude, types, amapWebServiceKey){
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      // 高德地图
      wx.request({
        url: getApp().data.amapRound,
        data: {
          location: longitude+","+latitude,
          radius: 1500,
          output: 'json',
          types: types,
          offset: 3,
          page: 1,
          key: amapWebServiceKey
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success: function (res) {
          let result="";
          console.log(res);
          resolve(res.data);
          updateAmapTimes(amapWebServiceKey);
        },
        fail: function (err) {
          wx.showToast({
            title: "获取周边信息失败",
            icon: "none"
          });
          reject(err);
        }
      });
    },500)
  });
}

//根据坐标获取位置名称
function getRoundInfo2(longitude, latitude, types, amapWebServiceKey){
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      // 高德地图
      wx.request({
        url: getApp().data.amapRound,
        data: {
          location: longitude+","+latitude,
          radius: 1500,
          output: 'json',
          types: types,
          offset: 8,
          page: 1,
          key: amapWebServiceKey
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success: function (res) {
          let result="";
          console.log("成功了吗？");
          console.log(res);
          resolve(res.data);
          updateAmapTimes(amapWebServiceKey);
        },
        fail: function (err) {
          wx.showToast({
            title: "获取周边信息失败",
            icon: "none"
          });
          reject(err);
        }
      });
    },500)
  });
}

//根据坐标获取位置名称
function getRoundSchool(longitude, latitude, types, amapWebServiceKey){
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      // 高德地图
      wx.request({
        url: getApp().data.amapRound,
        data: {
          location: longitude+","+latitude,
          radius: 1500,
          output: 'json',
          types: 141201|141202|141203,
          offset: 8,
          page: 1,
          key: amapWebServiceKey
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success: function (res) {
          let result="";
          console.log("成功了吗？");
          console.log(res);
          resolve(res.data);
          updateAmapTimes(amapWebServiceKey);
        },
        fail: function (err) {
          wx.showToast({
            title: "获取周边信息失败",
            icon: "none"
          });
          reject(err);
        }
      });
    },500)
  });
}


//根据坐标获取位置名称
function getRoundBusinessInfo(longitude, latitude, types, amapWebServiceKey){
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      // 高德地图
      wx.request({
        url: getApp().data.amapRound,
        data: {
          location: longitude+","+latitude,
          radius: 990,
          output: 'json',
          types: types,
          key: amapWebServiceKey
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success: function (res) {
          let result="";
          console.log(res);
          resolve(res.data);
          updateAmapTimes(amapWebServiceKey);
        },
        fail: function (err) {
          wx.showToast({
            title: "获取周边信息失败",
            icon: "none"
          });
          reject(err);
        }
      });
    },500)
  });
}

//根据坐标获取位置名称
function getAmapDistrictInfo(longitude, latitude, types, amapWebServiceKey){
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      // 高德地图
      wx.request({
        url: getApp().data.amapDistrict,
        data: {
          location: longitude+","+latitude,
          radius: 990,
          output: 'json',
          types: types,
          key: amapWebServiceKey
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success: function (res) {
          let result="";
          console.log(res);
          resolve(res.data);
          updateAmapTimes(amapWebServiceKey);
        },
        fail: function (err) {
          wx.showToast({
            title: "获取周边信息失败",
            icon: "none"
          });
          reject(err);
        }
      });
    },500)
  });
}

function arrayUnique(arr) {
  var result = [], hash = {};
  for (var i = 0, elem; (elem = arr[i]) != null; i++) {
    if (!hash[elem]) {
      result.push(elem);
      hash[elem] = true;
    }
  }

  return result;
}

// 获取签到打卡记录
function getCheckinRecord(id) {
  return fetchApi("outvisit/queryClockInfo?outvistId="+id, {
  }, "POST");
}

// 签到打卡
function checkin(id, longitude, latitude, address, remark) {
  wx.showLoading({
    title: '打卡中',
  });//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("outvisit/checkin", {
    body: {
      "checkInAddr": address,
      "latitude": latitude,
      "longitude": longitude,
      "outvisitId": id,
      "userId": userId,
      "remark": remark
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      wx.navigateBack({
        delta: 1,
        success: function () {
          wx.showToast({
            title: "打卡成功",
            icon: "none"
          });
        }
      });
    }
  })
}

// 获取外访场景列表
function getSceneData(ccode) {
  return fetchApi("outvisit/sceneData?code=" + ccode,{
  }, "POST");
}

//增加订单的功能
function makeSubmitAppointforApp(data) {
  var userId = wx.getStorageSync("userId");
  data.userId = userId;
  return fetchApi("surveydistribut/makeAppointforApp.shtml", {
    body: data
  }, "POST");
}

function saveSurveyRemarkApp(data) {
  var userId = wx.getStorageSync("userId");
  data.userId = userId;
  return fetchApi("surveydistribut/saveSurveyRemarkApp.shtml", {
    body: data
  }, "POST");
}

function addCaseColumnValueForApp(submitData,surveyColumnValList) {
  var userId = wx.getStorageSync("userId");
  submitData.userId = userId;
  return fetchApi("surveycase/addCaseinfosforApp.shtml", {
    body: {
      "submitData":submitData,
      "surveyColumnValList":surveyColumnValList
    }
  }, "POST");
}

function addCaseBaseInfoForApp(submitData) {
  var userId = wx.getStorageSync("userId");
  submitData.userId = userId;

  return fetchApi("surveydistribut/addCaseBaseInfoForApp.shtml", {
    body: {
      "submitData":submitData
    }
  }, "POST");
}

function getSurveyCaseInfoForApp(surveyId,orderNumber) {
  var userId = wx.getStorageSync("userId");

  return fetchApi("surveydistribut/getSurveyCaseInfoForApp.shtml", {
    body: {
      "surveyId": surveyId,
      "orderNumber": orderNumber
    }
  }, "POST");
}

function addSurveyColumnValueForApp(submitData,surveyColumnValList,folder) {
  var userId = wx.getStorageSync("userId");
  submitData.userId = userId;
  return fetchApi("distributinfo/addinfoforApp.shtml", {
    body: {
      "submitData":submitData,
      "surveyColumnValList":surveyColumnValList,
      "folder":folder,
    }
  }, "POST");
}

function addSurveyMapColumnValueForApp(distributid,colid,colval) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("distributinfo/addMapInfoForApp.shtml", {
    body: {
      "distributid": distributid,
      "colid": colid,
      "colval": colval,
      "userId": userId,
    }
  }, "POST");
}

function addSurveyLocationForApp(distributid,latitude,longitude,address,street,township) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("surveydistribut/addSurveyLocation.shtml", {
    body: {
      "distributid": distributid,
      "latitude": latitude,
      "longitude": longitude,
      "userId": userId,
      "address": address,
      "street": street,
      "township": township,
    }
  }, "POST");
}


//增加退单的功能
function addReturnSurveyForApp(data) {
  var userId = wx.getStorageSync("userId");
  data.userId = userId;
  return fetchApi("surveydistribut/addReturnSurveyForApp.shtml", {
    body: data
  }, "POST");
}

function getSurveyImgs(distributid,floder,housetype) {
  return fetchApi("surveydistribut/getSurveyImgs.shtml", {
    body: {
      "distributid": distributid,
      "floder": floder,
      "housetype": housetype
    }
  }, "POST");
}

function updateSurveyCoordinate(longitude,latitude,locationName) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("surveydistribut/updateSurveyCoordinate.shtml", {
    body: {
      "longitude": longitude,
      "latitude": latitude,
      "locationName": locationName,
      "userId": userId,
    }
  }, "POST");
}


// 上传文件接口
function uploadFile(filePath, suveryId, housetype, floder) {
  var userId = wx.getStorageSync("userId");
  return promisify(wx.uploadFile)({
    url:`${API_URI}/surveydistribut/uploadvisit.shtml`,
    filePath: filePath,
    name: 'file',
    formData: {
      suveryId: suveryId,
      housetype: housetype,
      floder: floder
    }
  });
}

function uploadAttachmentFile(filePath, suveryId, housetype, floder) {
  var userId = wx.getStorageSync("userId");
  return promisify(wx.uploadFile)({
    url:`${API_URI}/surveydistribut/uploadvisitAttachment.shtml`,
    filePath: filePath,
    name: 'file',
    formData: {
      suveryId: suveryId,
      housetype: housetype,
      floder: floder,
      userId: userId
    }
  });
}

function deleteImage(suveryId, housetype, floder, path) {
  return fetchApi("surveydistribut/deleteImage.shtml", {
    body: {
      distributid: suveryId,
      housetype: housetype,
      floder: floder,
      path: path
    }
  }, "POST");
}

// 上传录音分片接口
function uploadRecordFrame(filePath, userId, outvisitTaskId, bufferNum) {
  return promisify(wx.uploadFile)({
    url: `${API_URI}/file/upload3`,
    filePath: filePath,
    name: 'file',
    formData: {
      userId: userId,
      outId: outvisitTaskId,
      index: bufferNum,
      name: "recorder.mp3",
    }
  });
}

// 合并录音分片接口
function mergeRecordFrame(collectionCaseId, originalFilePath, tempsFile) {
  return fetchApi("file/merge", {
    "collectionCaseId": collectionCaseId,
    "originalFilePath": originalFilePath,
    "tempsFile": tempsFile
  }, "POST", {
    "content-type": "application/x-www-form-urlencoded"
  });
}

// 删除文件接口
function deletdFile(fileIds) {
  return fetchApi("outvisit/del_record_file", {
    body: {
      "fileIds": fileIds
    }
  }, "POST");
}

// 终止任务
function stopOutvisit(id, cause) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("outvisit/stop_outvisit", {
    body: {
      "id": id,
      "revocationReason": cause,
      "userId": userId
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      // 获取上一个页面
      var pages = getCurrentPages();
      var page = pages[pages.length - 2];
      wx.navigateBack({
        delta: 1,
        success: function () {
          wx.showToast({
            title: "成功",
            icon: "none"
          });
          // 刷新我的任务列表页
          if (page.data.type == 1) {
            page.updateList();
          // 刷新地图页
          } else if (page.data.type == 0){
            page.getTaskList();
            page.setData({
              taskInfoIsHide: true
            });
          }
        }
      });
    }
  });
}

// 完成任务
function surveyComplete(comdistributid) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");

  console.log("即将完成任务");
  return fetchApi("surveydistribut/completed.shtml", {
    body: {
      comdistributid: comdistributid,
      platform: "3",
      userId: userId,
    }
  }, "POST");
}

function getSuveyColumnCompleteStatus(suveryId) {
  return fetchApi("surveydistribut/getSuveyColumnCompleteStatus.shtml", {
    body: {
      "id": suveryId
    }
  }, "POST");
}

// 完成任务
function surveyColumnComplete(suveryId, folder, userId) {
  return fetchApi("surveydistribut/addSurveyColumnComplete.shtml", {
    body: {
      "suveryId": suveryId,
      "folder": folder,
      "userId": userId
    }
  }, "POST");
}

// 回访
function returnVisits(id) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("clockout/backOutvisit?userId=" + userId + "&outvistId=" + id, {
  }, "POST").then(res => {
    if (res.code == 0) {
      wx.navigateBack({
        delta: 2,
        success: function () {
          wx.showToast({
            title: res.data,
            icon: "none"
          });
        }
      });
    }
  });
}

// 获取催收记录
function getCollectionRecord(id) {
  return fetchApi("app/html/collectionrecord?caseId=" + id, {
  }, "POST");
}

// 获取共债详情
function getTotalDebtDetails(id) {
  return fetchApi("app/html/totalDebtCase?caseId=" + id, {
  }, "POST");
}

// 获取外访审批列表
function getOutApprovalList(nowPage, pagesize) {
  var userId = wx.getStorageSync("userId");
  var companyId = wx.getStorageSync("companyId");
  return fetchApi("applyOutvisit/queryApply", {
    body: {
      "companyId": companyId,
      "userId": userId
    },
    header: {
      "nowPage": nowPage,
      "pagesize": pagesize
    }
  }, "POST");
}

// 获取外访审批详情
function getOutApprovaDetails(id) {
  return fetchApi("applyOutvisit/schduling?id=" + id, {
  }, "POST");
}

// 获取外访组
function getOutGroup(id) {
  var companyId = wx.getStorageSync("companyId");
  return fetchApi("applyOutvisit/outVistGroup?companyId=" + companyId, {
  }, "POST");
}

// 同意外访审批
function agreeOut(params) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("applyOutvisit/agreeOut", {
    body: {
      "userId": userId,
      ...params
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      // 获取上两个页面
      var pages = getCurrentPages();
      var page = pages[pages.length - 3];
      wx.navigateBack({
        delta: 2,
        success: function () {
          wx.showToast({
            title: "成功",
            icon: "none"
          });
          page.updateList();
        }
      });
    }
  });
}

// 撤销外访审批
function cancelOut(id, cause) {
  wx.showLoading();//显示加载中
  var userId = wx.getStorageSync("userId");
  return fetchApi("applyOutvisit/cancelOut", {
    body: {
      "userId": userId,
      "id": id,
      "stopReason": cause
    }
  }, "POST").then(res => {
    if (res.code == 0) {
      // 获取上一个页面
      var pages = getCurrentPages();
      var page = pages[pages.length - 2];
      wx.navigateBack({
        delta: 1,
        success: function () {
          wx.showToast({
            title: "撤销成功",
            icon: "none"
          });
          page.updateList();
        }
      });
    }
  });
}

// 获取总体统计
function getCensusReports() {
  var userId = wx.getStorageSync("userId");
  var companyId = wx.getStorageSync("companyId");
  return fetchApi("census/censusReports?userId=" + userId + "&complyId=" + companyId, {
  }, "POST");
}

// 获取用户信息
function getUserInfo() {
  var userId = wx.getStorageSync("userId");
  console.log("userId================>"+userId);
  //var companyId = wx.getStorageSync("companyId");
  return fetchApi("login/getUser.shtml", {
    body: {
      userId: userId
    }
  }, "POST");
}

// 修改密码
function editPass(oldPassword, password) {
  var userId = wx.getStorageSync("userId");
  return fetchApi("login/editPassword.shtml", {
    body: {
      "newPass": password,
      "oldPass": oldPassword,
      "userId": userId
    }
  }, "POST");
}

// 获取消息列表
function getMsgList(nowPage, pagesize) {
  var userId = wx.getStorageSync("userId");
  var companyId = wx.getStorageSync("companyId");
  return fetchApi("msg/msg_list", {
    body: {
      "companyId": companyId,
      "userId": userId
    },
    header: {
      "nowPage": nowPage,
      "pagesize": pagesize
    }
  }, "POST");
}

module.exports = {
  promisify,
  fetchApi,
  fetchApi2,
  login,
  logout,
  getUserRole,
  getClockInRecord,
  getVisitToday,
  clockIn,
  getTaskList,
  getAllTaskList,
  getAppointmentList,
  delayedOut,
  scrambleAlone,
  copyValues,
  getTaskDetails,
  getAppointmentDetails,
  getLocationByName,
  getLocationName,
  updateAmapTimes,
  getUsfulAmapInfo,
  getRoundInfo1,
  getRoundInfo2,
  getRoundBusinessInfo,
  getRoundSchool,
  getAmapDistrictInfo,
  getCheckinRecord,
  arrayUnique,
  checkin,
  getSceneData,
  addReturnSurveyForApp,
  addSurveyMapColumnValueForApp,
  addSurveyLocationForApp,
  getSuveyColumnVal,
  getSuveyColumnValForAddCase,
  getSuveyColumnList,
  saveBigMapImage,
  saveSmallMapImage,
  makeSubmitAppointforApp,
  saveSurveyRemarkApp,
  addCaseColumnValueForApp,
  addCaseBaseInfoForApp,
  getSurveyCaseInfoForApp,
  addSurveyColumnValueForApp,
  getSurveyImgs,
  uploadFile,
  uploadAttachmentFile,
  deleteImage,
  uploadRecordFrame,
  mergeRecordFrame,
  deletdFile,
  stopOutvisit,
  surveyComplete,
  updateSurveyCoordinate,
  returnVisits,
  getCollectionRecord,
  getTotalDebtDetails,
  getOutApprovalList,
  getOutApprovaDetails,
  surveyColumnComplete,
  getSuveyColumnCompleteStatus,
  getOutGroup,
  agreeOut,
  cancelOut,
  getCensusReports,
  getUserInfo,
  editPass,
  getMsgList
}
